package com.sl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.sl.entity.PageResult;
import com.sl.entity.Result;
import com.sl.entity.StatusCode;
import com.sl.pojo.*;
import com.sl.service.*;
import com.sl.util.ValidateCodeUtils;
import com.sl.vo.CheckInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/check")
public class CheckInfoController {
    @Autowired
    private CompanyCheckService companyCheckService;
    @Autowired
    private CheckDocumentService checkDocumentService;
    @Autowired
    private DocumentService documentService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserService userService;


    @GetMapping("/all")
    public Result all (){
        Integer page = 1;
        Integer  pageSize = 10;
        Page<CompanyCheck> all = companyCheckService.findAll(page, pageSize);
        List<CheckInfoVO> voList=new ArrayList<>();
        for (CompanyCheck companyCheck : all.getResult()) {
            CheckInfoVO checkInfoVO = check2VO(JSON.toJSONString(companyCheck) );
           /*  CheckInfoVO checkInfoVO = new CheckInfoVO();
           BeanUtils.copyProperties(companyCheck,checkInfoVO);
            Integer companyId = companyCheck.getCompanyId();
            Company company = companyService.findById(companyId);
            BeanUtils.copyProperties(company,checkInfoVO);*/
            voList.add(checkInfoVO);
        }
        PageResult<CheckInfoVO> companyCheckPageResult = new PageResult<>(all.getTotal(), voList);
        return  new Result(true, StatusCode.OK,"所有检查记录",companyCheckPageResult);
    }

    /**
     * 根据企业信息创建检查任务
     * @param data
     * @return
     */
     @PostMapping("/adds")
     public Result addCheckInfo(@RequestBody String data){
         log.info("创建检查任务,1条或N条>>>>" );
         List<HashMap> hashMaps = JSONArray.parseArray(data, HashMap.class);
         System.out.println(hashMaps);
         for (int i = 0; i < hashMaps.size(); i++) {
             Integer companyId = (Integer)hashMaps.get(i).get("companyId");
             CompanyCheck companyCheck = new CompanyCheck();
             String uustr=  createUUID();
             companyCheck.setUuid(uustr);
             companyCheck.setCompanyId(companyId);
             companyCheck.setAddTime(LocalDate.now());
             companyCheck.setChecked(0);
             companyCheck.setUserIds(hashMaps.get(i).get("userIds").toString());
             companyCheckService.addCompanyCheck(companyCheck);
             //1创建检查任务。2去中间表创建6张对应表。3用6张表ID，同时去文件表创建6张空文件行
             for (int f = 1; f < 7; f++) {
                 log.info("创建检查文件中间表第" + f +  "条>>>>" );
                 CheckDocument checkDocument = new CheckDocument();
                 checkDocument.setCheckUuid(uustr);
                 String docUuid= uustr + f ;
                 checkDocument.setDocUuid(docUuid);
                 checkDocumentService.addCD(checkDocument);
                 Document document = new Document();
                 document.setDocUuid(docUuid);//docId 不是document的ID。是document的docId
                 //documentService.addDocument(document);
             }
         }
        return  new Result(true, StatusCode.OK,"创建检查任务成功");
     }

    @PostMapping("/search")
    public Result findList(@RequestBody String data){
        log.info("多条件搜索检查结果>>>" + data);
        JSONObject jsonObject = JSON.parseObject(data);
        String company = jsonObject.getString("data");
      Map<String,Object> map=  JSON.parseObject(company);
          String users =(String) map.get("user");
        if(!StringUtils.isEmpty(users)){
            Integer userId = userService.findByName(users).getId();
            System.out.println("userId>>>" + userId);
            map.put("userIds",userId);
            System.out.println("map>>>" + map);
        }
        Integer page = jsonObject.getInteger("page");
        if (null ==page) {page=1;}
        Integer pageSize = jsonObject.getInteger("pageSize");
        if (null ==pageSize) {pageSize = 10;}
        log.info(">>>map" + map +">>>page" + page +">>>pageSize" + pageSize  );
        Page<CompanyCheck> list = companyCheckService.findList(map,page,pageSize);
        List<CheckInfoVO> voList=new ArrayList<>();
        for (CompanyCheck companyCheck : list) {
            CheckInfoVO checkInfoVO = check2VO(JSON.toJSONString(companyCheck));
            voList.add(checkInfoVO);
        }
        PageResult<CheckInfoVO> companyCheckPageResult = new PageResult<>(list.getTotal(),voList);
        return new Result(true, StatusCode.OK,"多条件查询",companyCheckPageResult);
    }

    /**
     * 更新检查信息:级别更改，时间更改，描述更改
     * @param data
     * @return
     */
    @PostMapping(value="/update")
    public Result update(@RequestBody String data){
        log.info("更新检查信息:级别更改，时间更改，描述更改" );
        if(StringUtils.isEmpty(data)){ return  new Result(true, StatusCode.ERROR,"参数为空");}
        CompanyCheck companyCheck = JSON.parseObject(data, CompanyCheck.class);
        companyCheck.setCheckTime(LocalDate.now());
        companyCheckService.updateCompanyCheck(companyCheck);
        return new Result(true, StatusCode.OK,"更新检查信息:级别更改，时间更改，描述更改");
    }

    @DeleteMapping(value="/delete")
    public Result deleteCompanyCheck(@RequestBody String data){
        CompanyCheck companyCheck = JSON.parseObject(data, CompanyCheck.class);
        String uuid = companyCheck.getUuid();
        companyCheckService.deletedCC(companyCheck);
        checkDocumentService.deleteCDByCheckUuid(uuid);

        return new Result(true, StatusCode.OK,"删除成功");
    }

    //查询一个月内的数据
    @GetMapping("/month/{yearMonth}")
    public  Result findMonth(@PathVariable String yearMonth){
        log.info("入参的月份>>>" + yearMonth);
        LocalDate localDate = LocalDate.parse(yearMonth+"-01");
        LocalDate firstDay = localDate.with(TemporalAdjusters.firstDayOfMonth());
        log.info("当月第一天日期>>>" + firstDay);
        LocalDate lastDay = localDate.with(TemporalAdjusters.lastDayOfMonth());
        log.info("当月最后一天日期>>>" + lastDay);
        List<Map> monthList = companyCheckService.findListByMonth(firstDay,lastDay);

        Map map=new HashMap();
        map.put("total",monthList.size());
        map.put("rows",monthList);
       // log.info("满足条件的当月数据>>>" + map);
        return new Result(true, StatusCode.OK,"检查信息:一个月内的数据",map);
    }

    //企业合格率统计。
    @GetMapping("/pass/{yearMonth}")
    public  Result passAndDesc(@PathVariable String yearMonth){
        log.info("入参的月份>>>" + yearMonth);
        LocalDate localDate = LocalDate.parse(yearMonth+"-01");
        LocalDate firstDay = localDate.with(TemporalAdjusters.firstDayOfMonth());
        log.info("当月第一天日期>>>" + firstDay);
        LocalDate lastDay = localDate.with(TemporalAdjusters.lastDayOfMonth());
        log.info("当月最后一天日期>>>" + lastDay);
        List<Map> monthList = companyCheckService.findListByMonth(firstDay,lastDay);
        int totalSize = monthList.size();
        log.info("当月检查企业数量>>>" + totalSize);
        int passSize= companyCheckService.passCompanyTotal(firstDay,lastDay);
        log.info("当月通过企业数量>>>" + passSize);
        DecimalFormat df=new DecimalFormat("0.00");
        String pass = df.format(((float) passSize / totalSize)*100);
        return new Result(true, StatusCode.OK,"检查信息:一个月内的合格数据","" + pass +"%");
    }

    @GetMapping("/{checkUuid}")
    public  Result oneCheckInfo(@PathVariable String checkUuid){
        Map<String,Object> map=new HashMap<>();
        CompanyCheck companyCheck = companyCheckService.findByUUId(checkUuid);

        map.put("checkInfo",check2VO(JSON.toJSONString(companyCheck)));
        List<CheckDocument> cdByCheckUuid = checkDocumentService.findCDByCheckUuid(checkUuid);

        List<String> docUuidList=new ArrayList<>();
        for (CheckDocument checkDocument : cdByCheckUuid) {
            docUuidList.add(checkDocument.getDocUuid());
        }
        map.put("docUuid",docUuidList);

        return new Result(true, StatusCode.OK,"检查信息一条",map);
    }

    //测试 日期常用对比
/*    public static void main(String[] args) {
        //获取当前年月日
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        int year1 = localDate.get(ChronoField.YEAR);
        Month month = localDate.getMonth();
        int month1 = localDate.get(ChronoField.MONTH_OF_YEAR);
        int day = localDate.getDayOfMonth();
        int day1 = localDate.get(ChronoField.DAY_OF_MONTH);
        DayOfWeek dayOfWeek = localDate.getDayOfWeek();
        int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK);

        System.out.println(year+"year"+">>>>"+year1+"year1");//2020
        System.out.println("month" +">>>>"+ month);//FEBRUARY
        System.out.println("month1" +">>>>"+ month1);//2
        System.out.println("day::" + day + ">>>>"+"day1::" + day1  );//22
        System.out.println("dayOfWeek::" + dayOfWeek +">>>>"+ "dayOfWeek1::" + dayOfWeek1  );//SATURDAY>>6
    }*/


 public String createUUID(){
    // SimpleDateFormat st2 = new SimpleDateFormat("yyyyMMddHHmmss");
     SimpleDateFormat st2 = new SimpleDateFormat("yyyyMMdd");
     Date date = new Date();
     Integer integer = ValidateCodeUtils.generateValidateCode(6);
     return st2.format(date) + integer;
 }
//CompanyCheck companyCheck
 //@RequestMapping("/check2VO")
 private CheckInfoVO check2VO(String data) {
    log.info("转换为公司检查视图对象");
     JSONObject jsonObject = JSON.parseObject(data);
     //获取公司
     Integer companyId = jsonObject.getInteger("companyId");
     Company company = companyService.findById(companyId);
     if(null ==company){throw new RuntimeException("没有这个公司");}
     CheckInfoVO checkInfoVO = new CheckInfoVO();
     //公司信息--》检查信息
     BeanUtils.copyProperties(company,checkInfoVO);

     //检查信息
     checkInfoVO.setUuid(jsonObject.getString("uuid"));
     checkInfoVO.setAddTime(jsonObject.getString("addTime"));
     checkInfoVO.setCheckTime(jsonObject.getString("checkTime"));
     checkInfoVO.setLevel(jsonObject.getString("level"));
     checkInfoVO.setDescription(jsonObject.getString("description"));
     checkInfoVO.setChecked(jsonObject.getInteger("checked"));

     //获取用户信息
     JSONArray userIds = jsonObject.getJSONArray("userIds");
     if(null !=userIds) {
         List<String> userList = new ArrayList<>();
         for (Object userId : userIds) {
             User byId = userService.findById((Integer) userId);
             userList.add(byId.getName());
         }
         checkInfoVO.setUsers(userList.toString());
     }
     return checkInfoVO;
 }

}
